package mapper;

import mapper.entity.Connector;
import mapper.entity.Context;
import mapper.entity.Host;
import mapper.entity.Wrapper;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import server.HttpServlet;

import java.io.File;
import java.io.InputStream;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

/**
 * Created by Ju·Felix on 2020/5/17.
 */
public class Mapper {

    private List<Connector> connectorList = new ArrayList<>();
    private List<Host> hostList = new ArrayList<>();

    public List<Connector> getConnectors() {
        return connectorList;
    }

    public HttpServlet getHandler(String hostName, String requetUrl) {

        String tmpStr = requetUrl.substring(1);
        String contextName = tmpStr.substring(0, tmpStr.indexOf("/"));

        Optional<HttpServlet> servletOptional = hostList.stream()
                // 第一层：过滤host
                .filter(host -> host.getName().equals(hostName))
                .map(host -> host.findHttpServlet(contextName, requetUrl))
                .filter(Objects::nonNull)
                .findFirst();

        if (servletOptional.isEmpty()) {
            return null;
        }

        return servletOptional.get();
    }

    /**
     * 解析 server.xml
     */
    public void init() {
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("server.xml");
        SAXReader saxReader = new SAXReader();

        try {
            Document document = saxReader.read(resourceAsStream);
            Element rootElement = document.getRootElement();

            // 一个 Server 中有多个Service
            List<Element> selectNodes = rootElement.selectNodes("//Service");
            for (int i = 0; i < selectNodes.size(); i++) {
                Element element = selectNodes.get(i);


                // 一个Service中有多个Connector实例，解析并封装为Connector对象，填充到 connectorList 中
                List<Element> connectorElements = element.selectNodes("Connector");
                connectorElements.forEach(connEle -> {
                    String onePort = connEle.attribute("port").getValue();
                    Connector connector = new Connector(Integer.valueOf(onePort));
                    connectorList.add(connector);
                });

                // 一个Service中有一个Engine
                Element engine = (Element) element.selectSingleNode("Engine");
                // 一个Engine下有多个Host
                List<Element> hostElements = engine.selectNodes("Host");
                // 获取Host的属性值，并解析出对应的context和wrapper
                hostElements.forEach(hostEle -> {
                    String hostName = hostEle.attribute("name").getValue();
                    String oneClassPath = hostEle.attribute("appBase").getValue();
                    List<Context> contexts = buildContexts(oneClassPath);
                    Host host = new Host(hostName, contexts);
                    hostList.add(host);
                });

            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private List<Context> buildContexts(String oneClassPath) {
        List<Context> contexts = new ArrayList<>();
        File webappsDir = new File(oneClassPath);
        for (File file : Objects.requireNonNull(webappsDir.listFiles())) {
            if (file.isDirectory()) {
                String contextName = file.getName();
                String contextPath = file.getAbsolutePath();
                List<Wrapper> wrappers = buildWrappers(contextPath);
                Context context = new Context(contextName, wrappers);
                contexts.add(context);
            }
        }

        return contexts;
    }

    private List<Wrapper> buildWrappers(String contextPath) {
        String webXmlLocation = contextPath + File.separator + "web.xml";

        List<Wrapper> wrappers = new ArrayList<>();
        try {
            // 由于是加载外部文件夹中的class文件，这里使用 new File 的方式获取文件流
            File file = new File(webXmlLocation);

            // 获取context的URL定位
            File contextPathFile = new File(contextPath);
            URL contextUrl = contextPathFile.toURI().toURL();

            SAXReader saxReader = new SAXReader();
            Document document = saxReader.read(file);
            Element rootElement = document.getRootElement();

            List<Element> selectNodes = rootElement.selectNodes("//servlet");
            for (int i = 0; i < selectNodes.size(); i++) {
                Element element = selectNodes.get(i);
                // <servlet-name>lagou</servlet-name>
                Element servletnameElement = (Element) element.selectSingleNode("servlet-name");
                String servletName = servletnameElement.getStringValue();
                // <servlet-class>server.LagouServlet</servlet-class>
                Element servletclassElement = (Element) element.selectSingleNode("servlet-class");
                String servletClassName = servletclassElement.getStringValue();

                // 根据servlet-name的值找到url-pattern
                Element servletMapping = (Element) rootElement.selectSingleNode("/web-app/servlet-mapping[servlet-name='" + servletName + "']");
                String urlPattern = servletMapping.selectSingleNode("url-pattern").getStringValue();

                // 通过类加载器加载到该类
                URLClassLoader loader = new URLClassLoader(new URL[]{contextUrl}, this.getClass().getClassLoader());
                Class<?> servletClass = loader.loadClass(servletClassName);
                HttpServlet httpServlet = (HttpServlet) servletClass.newInstance();

                // 封装到Wrapper
                Wrapper wrapper = new Wrapper(urlPattern, httpServlet);
                wrappers.add(wrapper);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return wrappers;
    }

}
